import React, {useEffect, useRef, useState} from 'react';
import {Check, Grid, List, Plus, Trash2, Upload, Video, X} from 'lucide-react';
import {Req, UploadFile} from '../../util/fetch';


interface MediaItem {
    id: number;
    type: string;
    url: string;
    name: string;
    thumbnail?: string;
    tags: string[];
    selected?: boolean;
    size: string;
}

interface Training {
    id: number;
    title: string;
}

interface MediaManageModalProps {
    training: Training;
    onClose: () => void;
}

const availableTags = [
    '破冰游戏',
    '团建活动',
    '培训视频',
    '精彩回顾',
    '团队合影',
    '活动记录',
    '精彩片段'
];

export default function MediaManageModal({training, onClose}: MediaManageModalProps) {
    const [mediaItems, setMediaItems] = useState<MediaItem[]>([]);
    const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
    const [selectedTags, setSelectedTags] = useState<string[]>([]);
    const [newTag, setNewTag] = useState('');
    const [showTagInput, setShowTagInput] = useState(false);
    const fileInputRef = useRef<HTMLInputElement | null>(null); // 创建文件输入引用


    const handleAddTag = () => {
        if (newTag && !selectedTags.includes(newTag)) {
            setSelectedTags([...selectedTags, newTag]);
            setNewTag('');
            setShowTagInput(false);
        }
    };

    const handleRemoveTag = (tag: string) => {
        setSelectedTags(selectedTags.filter(t => t !== tag));
    };

    const handleDeleteMedia = (id: number, name: string) => {
        if (id) {
            setMediaItems(mediaItems.filter(item => item.id !== id));
        } else {
            setMediaItems(mediaItems.filter(item => item.name !== name));
        }
    };

    const toggleMediaSelection = (id: number) => {
        setMediaItems(mediaItems.map(item =>
            item.id === id ? {...item, selected: !item.selected} : item
        ));
    };

    const handleApplyTags = () => {
        if (selectedTags.length === 0) return;

        setMediaItems(mediaItems.map(item =>
            item.selected ? {
                ...item,
                tags: [...new Set([...item.tags, ...selectedTags])],
                selected: false
            } : item
        ));
        setSelectedTags([]);
    };

    const selectedCount = mediaItems.filter(item => item.selected).length;

    const handleSelectFileClick = () => {
        if (fileInputRef.current) {
            fileInputRef.current.click(); // 触发文件输入的点击事件
        }
    };

    const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (!files) return;
        const fileType = getFileType(files[0].name)
        const res = await UploadFile(fileType == 'video' ? 1 : 0, files[0])
        setMediaItems([...mediaItems, {
            id: null,
            type: getFileType(res.data.fileName),
            url: res.data.url,
            name: res.data.fileName,
            thumbnail: res.data.thumbnail,
            tags: [],
            size: Math.floor(files[0].size / 1024) + 'KB',
        }]);
        console.log('handleFileChange', files, res);
    };

    const saveMediaItems = async () => {
        console.log('saveMediaItems', mediaItems);
        const list = []
        let i = 0
        mediaItems.forEach(item => {
            list.push({
                // id: item.id,
                trainId: training.id,
                filePath: item.url,
                fileName: item.name,
                fileSize: item.size,
                thumbnail: item.thumbnail,
                fileType: item.type,
                sort: i,
                tags: item.tags.join(','),
            })
            i++;
        })
        const res = await Req('/bsTrainMedia/add', {
            method: 'POST',
            body: {
                trainId: training.id,
                list
            },
            headers: undefined
        })
        if (res.success) {
            alert(res.message)
            onClose()
        } else {
            alert(res.message)
        }
    };

    const getFileType = (name: string) => {
        const fileName = name.toLowerCase()
        if (fileName.endsWith('.mp4')) {
            return 'video';
        } else if (fileName.endsWith('.jpg')
            || fileName.endsWith('.jpeg')
            || fileName.endsWith('.png')
            || fileName.endsWith('.svg')
            || fileName.endsWith('.avif')
        ) {
            return 'image';
        }
        return 'unknown';
    }

    const queryList = async (id) => {
        const res = await Req(`/bsTrainMedia/list?trainId=${id}`)
        if (res.success) {
            setMediaItems(res.data.map((item) => {
                return {
                    id: item.id,
                    name: item.fileName,
                    size: item.fileSize,
                    type: item.fileType,
                    url: item.filePath,
                    thumbnail: item.thumbnail,
                    tags: item.tags ? item.tags.split(',').filter(tag => tag.trim() != '') : [],
                }
            }));
        } else {
            alert(res.message)
        }
    };

    useEffect(() => {
        queryList(training.id)
    }, [])

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
            <div className="bg-white rounded-lg w-full max-w-6xl mx-4 max-h-[90vh] flex flex-col">
                <div className="flex items-center justify-between p-4 border-b">
                    <h3 className="text-lg font-semibold text-gray-900">媒体管理</h3>
                    <div className="flex items-center space-x-4">
                        <div className="flex bg-gray-100 rounded-lg p-1">
                            <button
                                onClick={() => setViewMode('grid')}
                                className={`p-2 rounded-lg ${
                                    viewMode === 'grid' ? 'bg-white shadow-sm text-blue-500' : 'text-gray-500'
                                }`}
                                title="网格视图"
                            >
                                <Grid className="w-5 h-5"/>
                            </button>
                            <button
                                onClick={() => setViewMode('list')}
                                className={`p-2 rounded-lg ${
                                    viewMode === 'list' ? 'bg-white shadow-sm text-blue-500' : 'text-gray-500'
                                }`}
                                title="列表视图"
                            >
                                <List className="w-5 h-5"/>
                            </button>
                        </div>
                        <button onClick={onClose}>
                            <X className="w-6 h-6 text-gray-500"/>
                        </button>
                    </div>
                </div>

                <div className="p-6 flex-1 overflow-y-auto">
                    {/* 上传区域 */}
                    <div className="mb-6">
                        <div className="border-2 border-dashed rounded-lg p-6 text-center">
                            <Upload className="mx-auto h-12 w-12 text-gray-400"/>
                            <p className="mt-2 text-gray-600">点击选择文件上传</p>
                            <p className="text-sm text-gray-500">支持视频文件</p>
                            <input
                                type="file"
                                className="hidden"
                                accept="video/*,image/*"
                                multiple
                                ref={fileInputRef}
                                onChange={handleFileChange}
                            />
                            <button
                                onClick={handleSelectFileClick}
                                className="mt-4 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
                                选择文件
                            </button>
                        </div>
                    </div>

                    {/* 批量操作区域 */}
                    {selectedCount > 0 && (
                        <div className="mb-6 bg-blue-50 rounded-lg p-4">
                            <div className="flex items-center justify-between mb-3">
                                <span className="text-blue-700 font-medium">
                                  已选择 {selectedCount} 个文件
                                </span>
                                <button
                                    onClick={() => setMediaItems(mediaItems.map(item => ({...item, selected: false})))}
                                    className="text-blue-600 hover:text-blue-800 text-sm"
                                >
                                    取消选择
                                </button>
                            </div>
                            <div className="flex flex-wrap gap-2 items-center">
                                <span className="text-sm text-gray-600">添加标签：</span>
                                {selectedTags?.map(tag => (
                                    <span
                                        key={tag}
                                        className="flex items-center bg-white text-blue-600 px-3 py-1 rounded-full text-sm"
                                    >
                                        {tag}
                                        <button
                                            onClick={() => handleRemoveTag(tag)}
                                            className="ml-2 text-blue-400 hover:text-blue-600"
                                        >
                                          <X className="w-4 h-4"/>
                                        </button>
                                      </span>
                                ))}
                                {showTagInput ? (
                                    <div className="flex items-center space-x-2">
                                        <input
                                            type="text"
                                            value={newTag}
                                            onChange={(e) => setNewTag(e.target.value)}
                                            className="px-3 py-1 border rounded-full text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            placeholder="输入标签"
                                            onKeyPress={(e) => e.key === 'Enter' && handleAddTag()}
                                        />
                                        <button
                                            onClick={handleAddTag}
                                            className="text-blue-600 hover:text-blue-800"
                                        >
                                            <Check className="w-4 h-4"/>
                                        </button>
                                    </div>
                                ) : (
                                    <button
                                        onClick={() => setShowTagInput(true)}
                                        className="flex items-center text-blue-600 hover:text-blue-800 px-3 py-1 rounded-full text-sm bg-white"
                                    >
                                        <Plus className="w-4 h-4 mr-1"/>
                                        添加标签
                                    </button>
                                )}
                                <button
                                    onClick={handleApplyTags}
                                    className="ml-auto px-3 py-1 bg-blue-500 text-white rounded-full text-sm hover:bg-blue-600"
                                >
                                    应用标签
                                </button>
                            </div>
                            <div className="mt-3">
                                <span className="text-sm text-gray-600 mr-2">常用标签：</span>
                                <div className="flex flex-wrap gap-2 mt-2">
                                    {availableTags.map(tag => (
                                        <button
                                            key={tag}
                                            onClick={() => !selectedTags.includes(tag) && setSelectedTags([...selectedTags, tag])}
                                            className={`px-3 py-1 rounded-full text-sm ${
                                                selectedTags.includes(tag)
                                                    ? 'bg-blue-500 text-white'
                                                    : 'bg-white text-gray-600 hover:bg-gray-50'
                                            }`}
                                        >
                                            {tag}
                                        </button>
                                    ))}
                                </div>
                            </div>
                        </div>
                    )}

                    {/* 媒体列表 */}
                    {viewMode === 'grid' ? (
                        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                            {mediaItems.map(item => (
                                <div
                                    key={item.id + item.name}
                                    className={`relative group ${
                                        item.selected ? 'ring-2 ring-blue-500 rounded-lg' : ''
                                    }`}
                                >
                                    <div
                                        className="aspect-video rounded-lg overflow-hidden bg-gray-100 cursor-pointer"
                                        onClick={() => toggleMediaSelection(item.id)}
                                    >
                                        <img
                                            src={item.type === 'video' ? item.thumbnail : item.url}
                                            alt=""
                                            className="w-full h-full object-cover"
                                        />
                                        {item.type === 'video' && (
                                            <div
                                                className="absolute inset-0 flex items-center justify-center bg-black/30">
                                                <Video className="w-12 h-12 text-white"/>
                                            </div>
                                        )}
                                    </div>
                                    <div
                                        className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                        <button
                                            onClick={() => handleDeleteMedia(item.id, item.name)}
                                            className="p-2 bg-red-500 text-white rounded-full hover:bg-red-600"
                                        >
                                            <Trash2 className="w-5 h-5"/>
                                        </button>
                                    </div>
                                    <div className="mt-2 flex flex-wrap gap-1">
                                        {item.tags.map((tag, index) => (
                                            <span
                                                key={index}
                                                className="px-2 py-1 bg-gray-100 text-gray-600 rounded-full text-xs"
                                            >
                        {tag}
                      </span>
                                        ))}
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : (
                        <div className="space-y-3">
                            {mediaItems.map(item => (
                                <div
                                    key={item.id}
                                    className={`flex items-center space-x-4 p-4 rounded-lg ${
                                        item.selected ? 'bg-blue-50 border border-blue-200' : 'bg-white border border-gray-100'
                                    }`}
                                >
                                    <div className="flex-shrink-0">
                                        <input
                                            type="checkbox"
                                            checked={item.selected}
                                            onChange={() => toggleMediaSelection(item.id)}
                                            className="w-5 h-5 text-blue-600 rounded border-gray-300 focus:ring-blue-500"
                                        />
                                    </div>
                                    <div className="w-40 h-24 relative rounded-lg overflow-hidden flex-shrink-0">
                                        <img
                                            src={item.type === 'video' ? item.thumbnail : item.url}
                                            alt=""
                                            className="w-full h-full object-cover"
                                        />
                                        {item.type === 'video' && (
                                            <div
                                                className="absolute inset-0 flex items-center justify-center bg-black/30">
                                                <Video className="w-8 h-8 text-white"/>
                                            </div>
                                        )}
                                    </div>
                                    <div className="flex-1">
                                        <div className="flex flex-wrap gap-2 mb-2">
                                            {item.tags.map((tag, index) => (
                                                <span
                                                    key={index}
                                                    className="px-2 py-1 bg-gray-100 text-gray-600 rounded-full text-xs"
                                                >
                                                  {tag}
                                                </span>
                                            ))}
                                        </div>
                                        <div className="text-sm text-gray-500">
                                            {item.type === 'video' ? '视频文件' : '图片文件'}
                                        </div>
                                    </div>
                                    <button
                                        onClick={() => handleDeleteMedia(item.id, item.name)}
                                        className="p-2 text-gray-400 hover:text-red-500"
                                    >
                                        <Trash2 className="w-5 h-5"/>
                                    </button>
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                <div className="flex justify-end space-x-3 p-4 bg-gray-50 rounded-b-lg">
                    <button
                        onClick={onClose}
                        className="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"
                    >
                        关闭
                    </button>
                    <button
                        onClick={saveMediaItems}
                        className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
                        保存
                    </button>
                </div>
            </div>
        </div>
    );
}